package com.example.pictureview;

import android.app.Activity;
import android.content.ContentResolver;
import android.content.Context;
import android.content.Intent;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Bundle;
import android.provider.MediaStore;
import android.support.v4.view.ViewPager;

import com.example.pictureview.adapter.ImageAdapter;
import com.example.pictureview.utils.Utils;
import com.example.pictureview.widget.BaseImageLoader;

import java.util.ArrayList;
import java.util.List;


public class ImageBrowseActivity extends Activity {

    private ViewPager mViewPager;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_image_browse);
        mViewPager = (ViewPager) findViewById(R.id.view_pager);
        new ImageTask().execute();

    }

    public static void gotoActivity(Context context) {
        Intent intent = new Intent(context, ImageBrowseActivity.class);
        context.startActivity(intent);
    }

    class ImageTask extends AsyncTask<Void, Void, List<String>> {
        @Override
        protected List<String> doInBackground(Void... params) {
            final List<String> paths = new ArrayList<>();
            if (android.os.Environment.getExternalStorageState().equals(android.os.Environment.MEDIA_MOUNTED)) {

                Uri originalUri = MediaStore.Images.Media.EXTERNAL_CONTENT_URI;
                ContentResolver cr = ImageBrowseActivity.this.getApplicationContext().getContentResolver();
                Cursor cursor = cr.query(originalUri, null, null, null, null);
                if (cursor == null) {
                    return paths;
                }
                for (cursor.moveToFirst(); !cursor.isAfterLast(); cursor.moveToNext()) {
                    String path = cursor.getString(cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA));
                    paths.add(path);
                }
                cursor.close();

            }
            return paths;
        }

        @Override
        protected void onPostExecute(List<String> strings) {
            mViewPager.setAdapter(new ImageAdapter(ImageBrowseActivity.this, new MyImageLoader(), strings));

        }
    }

    private static class MyImageLoader extends BaseImageLoader {
        @Override
        protected Bitmap getBitmapFormUrl(String url) {
            return Utils.decodeBitmapFromFile(url, 100, 100);
        }
    }
}
